package com.icoolkj.ms.rbac.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.icoolkj.ms.common.cache.constant.CacheNames;
import com.icoolkj.ms.common.core.enums.UserTypeEnum;
import com.icoolkj.ms.rbac.bo.UriPermissionBO;
import com.icoolkj.ms.rbac.mapper.SysPermissionMapper;
import com.icoolkj.ms.rbac.service.ISysPermissionService;
import org.springframework.aop.framework.AopContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author icoolkj
 * @version 1.0
 * @description 权限业务层处理
 * @createDate 2025/02/16 17:58
 */
@Service
public class SysPermissionServiceImpl implements ISysPermissionService {

    @Autowired
    private SysPermissionMapper sysPermissionMapper;

    @Override
    public List<String> getUserMenuPermissions(Long userId, String userType) {
        SysPermissionServiceImpl sysPermissionService = (SysPermissionServiceImpl)AopContext.currentProxy();
        List<String> permsList;
        // 系统管理员，拥有最高权限
        if (ObjectUtil.equals(UserTypeEnum.SYSTEM_USER.getCode(), userType)) {
            permsList = sysPermissionService.listPermissionByUserIdAndUserType(userId, userType);
        } else {
            permsList = sysPermissionService.listPermissionByUserIdAndUserType(userId, userType);
        }
        return permsList;
    }


    @Cacheable(cacheNames = CacheNames.USER_PERMISSIONS_KEY, key = "#userType + ':' + #userId")
    public List<String> listPermissionByUserIdAndUserType(Long userId, String userType) {
        return sysPermissionMapper.listPermissionByUserIdAndUserType(userId, userType);
    }


    @Override
    @Caching(evict = {
            @CacheEvict(cacheNames = CacheNames.USER_PERMISSIONS_KEY, key = "#userType + ':' + #userId", condition = "#userId != null"),
            @CacheEvict(cacheNames = CacheNames.MENU_ID_LIST_KEY, key = "#userId", condition = "#userId != null")
    })
    public void clearUserPermissionsCache(Long userId, String userType){

    }

    @Override
    @Cacheable(cacheNames = CacheNames.URI_PERMISSION_KEY, key = "#userType")
    public List<UriPermissionBO> listUriPermissionInfo(String userType) {
        return sysPermissionMapper.listUriPermissionInfo(userType);
    }

    public List<String> selectRoleKeyListByUserId(Long userId, String userType) {
        return sysPermissionMapper.selectRoleKeyListByUserId(userId);
    }


}
